﻿using Corel.Interop.VGCore;
using NLog;
using NLog.Fluent;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Shapes;
using corel = Corel.Interop.VGCore;
using Shape = Corel.Interop.VGCore.Shape;

namespace HyperplaneTech.CdrPlugin {
    internal class AppManager {

        public static corel.Application cdrApp;

        /// <summary>
        /// 全局文件监听器
        /// </summary>
        public static FileSystemWatcher fileSystemWatcher;

        /// <summary>
        /// 日志记录器
        /// </summary>
        private static readonly Logger log = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 开始文件监控
        /// </summary>
        /// <param name="path"></param>
        public static void StartFileWatch(string path) {
            log.Info("开始监听文件夹：{}", path);
            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
            AppManager.fileSystemWatcher = fileSystemWatcher;
            fileSystemWatcher.Path = path;
            fileSystemWatcher.Created += FileSystemWatcher_Created;
            fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
            fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
            fileSystemWatcher.EnableRaisingEvents = true;
        }

        private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e) {
            try {
                // 如果是CDR文件，则将其打开
                if (e.Name.ToLower().EndsWith(".cdr")) {
                    // 搜索是否存在已经打开的文档
                    corel.Documents documents = AppManager.cdrApp.Documents;
                    bool exists = false;
                    foreach(Document doc in documents) {
                        if (doc.FilePath.Equals(e.FullPath)) {
                            exists = true;
                            break;
                        }
                    }
                    // 如果文件不存在，则打开
                    if (!exists) {
                        corel.Document doc = AppManager.cdrApp.OpenDocumentEx(e.FullPath, AppManager.cdrApp.CreateStructOpenOptions());
                        UploadDocShapeInfo(doc);
                    }
                    //corel.Document doc = AppManager.cdrApp.OpenDocumentEx(e.FullPath, AppManager.cdrApp.CreateStructOpenOptions());
                }
            } catch (Exception ex) {
                MessageBox.Show("处理文件监听发生异常：" + ex.Message);
            }
            //Console.WriteLine("File created: {0}", e.Name);
        }

        private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e) {
            //Console.WriteLine("File renamed: {0}", e.Name);
        }

        private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e) {
            //Console.WriteLine("File deleted: {0}", e.Name);
        }

        /// <summary>
        /// 上传文档形状信息
        /// </summary>
        /// <param name="doc">文档</param>
        private static void UploadDocShapeInfo(Document doc) {
            try {
                // 修改文档单位为毫米
                doc.Unit = cdrUnit.cdrMillimeter;
                List<MergedDataDto> mergedData = new List<MergedDataDto>();
                // 遍历文档的所有形状
                foreach(Shape s in doc.SelectableShapes) {
                    // 跳过参考线
                    if (s.Type == cdrShapeType.cdrGuidelineShape) {
                        continue;
                    }
                    // 如果是群组对象
                    if (s.Type == cdrShapeType.cdrGroupShape) {
                        // 取群组对象的整体信息
                        ShapeSizeDto rect = new ShapeSizeDto();
                        rect.width = s.SizeWidth;
                        rect.height = s.SizeHeight;
                        rect.x = s.PositionX;
                        rect.y = s.PositionY;
                        // 取群组对象内部的所有形状信息
                        List<ShapeSizeDto> rectList = new List<ShapeSizeDto>();
                        foreach (Shape innerShape in s.Shapes) {
                            ShapeSizeDto inner = new ShapeSizeDto();
                            inner.width = innerShape.SizeWidth;
                            inner.height = innerShape.SizeHeight;
                            inner.x = innerShape.PositionX;
                            inner.y = innerShape.PositionY;
                            rectList.Add(inner);
                        }
                        // 创建一个合并形状对象，添加到结果集
                        MergedDataDto dto = new MergedDataDto();
                        dto.rect= rect;
                        dto.rectList = rectList;
                        mergedData.Add(dto);
                    }
                }
                // 取得桌面的位置
                string desktopDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string localFile = desktopDir + "\\" + doc.Name + "_对象尺寸信息.json";
                File.WriteAllText(localFile, JsonUtil.ToJsonStr(mergedData));
                MessageBox.Show("对象数据已写入桌面文件：" + localFile);

                // 组装请求参数
                //RestClient client = new RestClient("https://yindaxia.com/api/Common/handleExternalParameters?order_sn=123456&fileResult=[%7B%22height%22:100,%22width%22:80,%22x%22:0,%22y%22:44%7D,%7B%22height%22:200,%22width%22:160,%22x%22:50,%22y%22:14%7D]");
                //RestRequest request = new RestRequest("", Method.Post);
                //request.AddHeader("Accept", "*/*");
                //request.AddHeader("Host", "yindaxia.com");
                //request.AddHeader("Connection", "keep-alive");
                //RestResponse response = client.Execute(request);
                //if (!response.IsSuccessful) {
                //    MessageBox.Show("调用[handleExternalParameters]接口失败，响应代码：" + response.StatusCode + "（" + response.StatusDescription + "）");
                //    return;
                //}
                //// 判断是否请求成功
                //JsonResult<object> result = JsonUtil.FromJSON<JsonResult<object>>(response.Content);
                //if (!(result.code == 200 || result.code == 204)) {
                //    MessageBox.Show("调用[handleExternalParameters]接口失败：" + result.msg);
                //    return;
                //}
                //MessageBox.Show("上传成功！");
            } catch (Exception ex) {
                MessageBox.Show("发送文档信息失败，文档名称：" + doc.Name + "，异常消息：" + ex.Message);
            }
        }

    }
}
